package cn.edu.bupt.freewings.forum.server.rest;

import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;

import org.apache.log4j.Logger;

import cn.edu.bupt.freewings.forum.persistence.User;
import cn.edu.bupt.freewings.forum.persistence.UserDAO;
import cn.edu.bupt.freewings.forum.persistence.EntityManagerHelper;
import cn.edu.bupt.freewings.forum.server.Utility.Converter;
import cn.edu.bupt.freewings.forum.server.Utility.MessageConstants;
import cn.edu.bupt.freewings.forum.common.UserType;
import cn.edu.bupt.freewings.forum.common.CommonType;

@Path("/user")
public class UserResource {
	@GET
	@Path("/get")
	@Produces( { "application/proto", "application/xml" })
	public UserType.User get(@QueryParam("id") @DefaultValue("1") Integer id,
			@QueryParam("name") @DefaultValue("") String name,
			@QueryParam("withPassword") @DefaultValue("true") Boolean withPassword) {
		User user = null;
		if (name != null && !"".equals(name))
			user = new UserDAO().findByName(name);
		else
			user = new UserDAO().findById(id);
		return Converter.userToUserType(user, withPassword);
	}

	@PUT
	@Path("/new")
	@Consumes({ "application/proto", "application/xml" })
	@Produces({ "application/proto", "application/xml" })
	public static CommonType.Boolean put(UserType.User userType){
		User newUser = Converter.UserTypeToUser(userType);
		EntityManagerHelper.beginTransaction();
		new UserDAO().save(newUser);
		EntityManagerHelper.commit();
		return MessageConstants.TRUE_MEESSAGE;
	}
	
	public static UserType.User getUserInfoById(Integer id){
		return new UserResource().get(id, null, false);
	}
	
	
}
